package longrise.phone.com.bjjt_henan.compensate;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.ui.AbstractSpinerAdapter.IOnItemSelectListener;
import com.longrise.bjjt.util.AllCapTransformationMethod;
import com.longrise.bjjt.util.StringUtils;
import com.longrise.bjjt.util.UiUtil;

import java.util.ArrayList;
import java.util.List;

import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.CheckCard;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.bindinginformation.BindCarView;

/**
 * 事故上传的信息填写界面，Created by Administrator on 2016/5/12.
 */
public class AccidentLoadingView extends LFView implements View.OnClickListener, IOnItemSelectListener, ILSMsgListener
        , AdapterView.OnItemSelectedListener {
    private String appCaseNo;//案件编号
    private Context context = null;
    private View view = null;
    private Button bt_accidentloading;
    private EditText et_accidentloadingpic1;
    private EditText et_accidentloadingpic2;
    private EditText et_accidentloadingpic3;
    private EditText et_accidentloadingpic4;
    private EditText et_accidentloadingpic5;
    private Button bt_accidentloading_record;
    private BaseApplication mApplication;
    private Dialog processDialog;
    private LinearLayout iv_loadingaccident;
    private EntityBean[] DrivingLicenceBeans;//车辆信息
    private EntityBean myDrivingLiscenceBean;//驾驶证的bean
    private List<String> carnoList = null;
    private RelativeLayout rl_accidentloading;
    private RadioGroup rg_accident1;
    private String dfCarType;
    private RadioButton rb_accident_1;
    private RadioButton rb_accident_2;
    private LinearLayout hn_btn_back;
    private TextView tv_title;
    private String accidentType;
    private String discription;
    private EditText et_accdentidcardhe;
    private EditText et_accdentidcardme;
    private Spinner carnoSpinner;
    private String selectShort;//选中的车牌首字母
    private EditText framnoET;//车架号

   /*public AccidentLoadingView(Context c) {
        super(c);
        this.context = c;
        this.mApplication = (BaseApplication) c.getApplicationContext();
    }

    public AccidentLoadingView(Context context, String appCaseNo) {
        super(context);
        this.context = context;
        this.appCaseNo = appCaseNo;
        this.mApplication = (BaseApplication) context.getApplicationContext();
    }

    public AccidentLoadingView(Context context, String appCaseNo, EntityBean myDrivingLiscenceBean) {
        super(context);
        this.context = context;
        this.appCaseNo = appCaseNo;
        this.mApplication = (BaseApplication) context.getApplicationContext();
        this.myDrivingLiscenceBean = myDrivingLiscenceBean;
    }*/

    public AccidentLoadingView(Context context, String appCaseNo, EntityBean myDrivingLiscenceBean, String accidentType, String discription) {
        super(context);
        this.context = context;
        this.appCaseNo = appCaseNo;
        this.mApplication = (BaseApplication) context.getApplicationContext();
        this.myDrivingLiscenceBean = myDrivingLiscenceBean;
        this.accidentType = accidentType;
        this.discription = discription;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void refresh() {
        checkBindingCarInfo();
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        initView();
        regEvent(true);
        initData();
    }

    //查询
    private void initData() {
        carnoList = new ArrayList<String>();
    }


    private void initView() {
        view = View.inflate(context, R.layout.view_accidentloading, null);
        bt_accidentloading = (Button) view.findViewById(R.id.bt_accidentloading);
        rg_accident1 = (RadioGroup) view.findViewById(R.id.rg_accident1);
        rb_accident_1 = (RadioButton) view.findViewById(R.id.rb_accident_1);
        rb_accident_2 = (RadioButton) view.findViewById(R.id.rb_accident_2);
        bt_accidentloading_record = (Button) view.findViewById(R.id.bt_accidentloading_record);
        et_accidentloadingpic1 = (EditText) view.findViewById(R.id.et_accidentloadingpic1);
        et_accidentloadingpic2 = (EditText) view.findViewById(R.id.et_accidentloadingpic2);
        et_accidentloadingpic3 = (EditText) view.findViewById(R.id.et_accidentloadingpic3);
        et_accidentloadingpic4 = (EditText) view.findViewById(R.id.et_accidentloadingpic4);
        et_accidentloadingpic5 = (EditText) view.findViewById(R.id.et_accidentloadingpic5);
        et_accdentidcardhe = (EditText) view.findViewById(R.id.et_accdentidcardhe);//对方驾驶证号
        et_accdentidcardme = (EditText) view.findViewById(R.id.et_accdentidcardme);//本方驾驶证号
        et_accdentidcardme.setText(myDrivingLiscenceBean.getString("cardno"));
        et_accidentloadingpic5.setText(myDrivingLiscenceBean.getString("carownername"));
        iv_loadingaccident = (LinearLayout) view.findViewById(R.id.iv_loadingaccident);
        rl_accidentloading = (RelativeLayout) view.findViewById(R.id.rl_accidentloading);
        hn_btn_back = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("事故上传");

        framnoET = (EditText) view.findViewById(R.id.et_frameno);
        carnoSpinner = (Spinner) view.findViewById(R.id.carno_spinner);
        initCarnoSpinner();
        //自动转换为大写
        et_accidentloadingpic2.setTransformationMethod(new AllCapTransformationMethod());
    }

    private void regEvent(boolean b) {
        if (null != hn_btn_back) {
            hn_btn_back.setOnClickListener(b ? this : null);
        }
        if (null != bt_accidentloading) {
            bt_accidentloading.setOnClickListener(b ? this : null);
        }
        if (null != bt_accidentloading_record) {
            bt_accidentloading_record.setOnClickListener(b ? this : null);
        }
        if (null != iv_loadingaccident) {
            iv_loadingaccident.setOnClickListener(b ? this : null);
        }
        if (null != rg_accident1) {
            rg_accident1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int i) {
                    switch (i) {
                        case R.id.rb_accident_1:
                            dfCarType = "1";
                            break;
                        case R.id.rb_accident_2:
                            dfCarType = "2";
                            break;
                    }
                }
            });
        }
        if (b) {
            this.addILSMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
        }
        if (null != carnoSpinner) {
            carnoSpinner.setOnItemSelectedListener(b ? this : null);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (view instanceof TextView) {
            TextView cView = (TextView) view;
            selectShort = cView.getText().toString().trim();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    private void initCarnoSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.simple_spinner_item,
                CommontUtils.getCarnoShorts());
        adapter.setDropDownViewResource(R.layout.item_spinner_dropdown);
        carnoSpinner.setAdapter(adapter);
        carnoSpinner.setSelection(0);//默认选中第一个，并执行监听
    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.hn_btn_back:
                    closeForm();
                    break;
                case R.id.bt_accidentloading_record:
                    BindCarView bindcarview = new BindCarView(context, null);
                    FrameworkManager.getInstance().showNewForm(context, bindcarview);
                    break;
                case R.id.iv_loadingaccident:
                    UiUtil.showSelectPopWindow(context, carnoList, this, rl_accidentloading, true);
                    break;
                case R.id.bt_accidentloading:
                    if (!ifEdittextNull()) {
                        return;
                    }
                    //对方车牌号
                    String otherCarno = et_accidentloadingpic2.getText().toString().trim().toUpperCase();
                    otherCarno = selectShort + otherCarno;
                    if (!StringUtils.isCar(otherCarno)) {
                        UiUtil.showToast(context, "对方的车牌号格式不正确");
                        return;
                    }
                    EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
                    String phoneNumber = userinfo.getString("mobilephone");
                    String phoneHis = et_accidentloadingpic3.getText().toString().trim();
                    //判断手机号是否正确
                    if (!StringUtils.isPhone(phoneHis)) {
                        UiUtil.showToast(context, "请输入正确的手机号");
                        return;
                    }
                    //判断双方的手机号是否相同
                    if (phoneHis.equals(phoneNumber)) {
                        UiUtil.showToast(context, "不能输入本人的手机号");
                        return;
                    }
                    if (null == dfCarType) {
                        UiUtil.showToast(context, "请选择车辆类型");
                        return;
                    }
                    String vin = framnoET.getText().toString().trim();
                    if (TextUtils.isEmpty(vin)) {
                        UiUtil.showToast(context, "请输入正确的车架号");
                        return;
                    }
                    String cardno = et_accdentidcardhe.getText().toString().trim();
                    if (!CheckCard.IDCardValidate(cardno)) {
                        UiUtil.showToast(context, "对方驾驶证号输入不正确");
                        return;
                    }
                    //提交
                    submit();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //创造双方的bean跳转,这是责任认定书的bean[]
    private void submit() {
        EntityBean hisBean = new EntityBean();
        hisBean.set("carType", dfCarType);
        hisBean.set("carownname", et_accidentloadingpic1.getText().toString().trim());
        hisBean.set("casecarno", selectShort + et_accidentloadingpic2.getText().toString().trim().toUpperCase());
        hisBean.set("casecarphone", et_accidentloadingpic3.getText().toString().trim());
        hisBean.set("casecarId", et_accdentidcardhe.getText().toString().trim());
        hisBean.set("frameno", framnoET.getText().toString().trim());

        EntityBean myBean = new EntityBean();
        myBean.set("carownname", et_accidentloadingpic5.getText().toString().trim());
        myBean.set("casecarno", et_accidentloadingpic4.getText().toString().trim());//车牌号
        myBean.set("casecarId", et_accdentidcardme.getText().toString().trim());//驾驶证号
        myBean.set("accidentType", accidentType);
        myBean.set("discription", discription);
        myBean.set("appCaseNo", appCaseNo);
        EntityBean[] disputeBean = new EntityBean[]{hisBean, myBean};

        //myDrivingLiscenceBean为驾驶证信息，DrivingLicenceBeans为查询的车辆信息，
        DisputeView disputeview = new DisputeView(context, myDrivingLiscenceBean, DrivingLicenceBeans, disputeBean);
        FrameworkManager.getInstance().showNewForm(context, disputeview);
    }

    /**
     * 判断输入框是否为空
     *
     * @return
     */
    private boolean ifEdittextNull() {
        String et_accidentloadingpic1content = et_accidentloadingpic1.getText().toString().trim();
        String et_accidentloadingpic2content = et_accidentloadingpic2.getText().toString().trim();
        String et_accidentloadingpic3content = et_accidentloadingpic3.getText().toString().trim();
        String et_accidentloadingpic4content = et_accidentloadingpic4.getText().toString().trim();
        String et_accidentloadingpic5content = et_accidentloadingpic5.getText().toString().trim();
        String et_accdentidcardhecontent = et_accdentidcardhe.getText().toString().trim();
        String et_accdentidcardmecontent = et_accdentidcardme.getText().toString().trim();
        if (!TextUtils.isEmpty(et_accidentloadingpic1content) && !TextUtils.isEmpty(et_accidentloadingpic2content)
                && !TextUtils.isEmpty(et_accidentloadingpic3content) && !TextUtils.isEmpty(et_accidentloadingpic4content)
                && !TextUtils.isEmpty(et_accidentloadingpic5content) && !TextUtils.isEmpty(et_accdentidcardhecontent) && !TextUtils.isEmpty(et_accdentidcardmecontent)) {
            return true;
        } else if (TextUtils.isEmpty(et_accidentloadingpic1content)) {
            UiUtil.showToast(context, "姓名为空");
            return false;
        } else if (TextUtils.isEmpty(et_accidentloadingpic2content)) {
            UiUtil.showToast(context, "对方车牌号为空");
            return false;
        } else if (TextUtils.isEmpty(et_accidentloadingpic3content)) {
            UiUtil.showToast(context, "联系电话为空");
            return false;
        } else if (TextUtils.isEmpty(et_accidentloadingpic4content)) {
            UiUtil.showToast(context, "我的车牌号为空");
            return false;
        } else if (TextUtils.isEmpty(et_accidentloadingpic5content)) {
            UiUtil.showToast(context, "当事人为空");
            return false;
        } else if (TextUtils.isEmpty(et_accdentidcardhecontent)) {
            UiUtil.showToast(context, "对方驾驶证号为空");
            return false;
        } else if (TextUtils.isEmpty(et_accdentidcardmecontent)) {
            UiUtil.showToast(context, "己方驾驶证号为空");
            return false;
        }
        return false;
    }

    @Override
    public void onItemClick(int pos, View view) {

        switch (view.getId()) {
            case R.id.rl_accidentloading:
                et_accidentloadingpic4.setText(carnoList.get(pos));
                //cartypeString = carTypeList.get(pos);
                break;

            default:
                break;
        }

    }


    //根据用户id查询用户绑定的车辆信息
    private void checkBindingCarInfo() {
        processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
        EntityBean bean = new EntityBean();
        EntityBean userInfo = mApplication.getLoginInfo().getBean("userinfo");
        bean.set("userid", userInfo.get("id"));
        bean.set("username", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());

        LoadDataManagerCar.getInstance(context).callService(null,
                mApplication.getServerUrl(), URLConstant.KCKPSEARCHCARS, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        Log.i("kckpSearchCars", "onSuccess--->" + result.toString());
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        EntityBean bean = (EntityBean) result;
                        String restate = bean.getString("restate");
                        String redes = bean.getString("redes");
                        if ("1".equals(restate)) {
                            DrivingLicenceBeans = bean.getBeans("data");
                            if (null != DrivingLicenceBeans && DrivingLicenceBeans.length > 0) {
                                carnoList.clear();
                                for (EntityBean eBean : DrivingLicenceBeans) {
                                    carnoList.add(eBean
                                            .getString("carno"));
                                }
                                //OCR识别对方车辆的相关信息
                                setOtherCarInfo(DrivingLicenceBeans[0]);
                            }
                        }
//                        else {
//                            UiUtil.showToast(context, redes);
//                        }
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                        if (resultType == LoadDataManagerFather.ResultType.Failure) {
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        } else if (resultType == LoadDataManagerFather.ResultType.NoNetWorks) {
                            UiUtil.showToast(context, "无网络连接，请检查您的网络");
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (null != processDialog) {
                            if (processDialog.isShowing()) {
                                processDialog.dismiss();
                            }
                        }
                    }
                });
    }

    //设置对方车辆的信息
    private void setOtherCarInfo(EntityBean otherBean) {
        try {
            if (otherBean == null) {
                return;
            }
            //车型
            String otype = otherBean.getString("ocartype");
            if (!TextUtils.isEmpty(otype)) {
                if (otype.startsWith("小型")) {
                    rb_accident_1.setChecked(true);
                } else if (otype.startsWith("大型")) {
                    rb_accident_2.setChecked(true);
                }
            }
            //姓名
            String oname = otherBean.getString("oname");
            if (CommontUtils.isChinaName(oname)) {
                et_accidentloadingpic1.setText(oname);
            }
            //车牌
            String ocarno = otherBean.getString("ocarno");
            if (StringUtils.isCar(ocarno)) {
                List<String> list = CommontUtils.getCarnoShorts();
                int pos = list.indexOf(ocarno.substring(0, 1));//截取表示区域的首汉字
                carnoSpinner.setSelection((pos == -1) ? 0 : pos);

                String end = ocarno.substring(1);
                et_accidentloadingpic2.setText(end);
            }
            //驾驶证号
            String ocardno = otherBean.getString("ocardno");
            if (CheckCard.IDCardValidate(ocardno)) {
                et_accdentidcardhe.setText(ocardno);
            }
            //车架号
            String ovin = otherBean.getString("ovin");
            if (CommontUtils.isCarvin(ovin)) {
                framnoET.setText(ovin);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object onLSMsg(int arg0, Object... arg1) {
        if (arg0 == 99) {
            //绑定成功调取查询车辆
            checkBindingCarInfo();
        }
        return null;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        view = null;
        regEvent(false);
        removeILSMsgListener(this);
    }
}
